' Stephen Toub


Imports Microsoft.VisualBasic
Imports System
Imports System.IO

Namespace C4F.DevKit.PreviewHandler.PreviewHandlerFramework
    Public MustInherit Class FileBasedPreviewHandlerControl
        Inherits PreviewHandlerControl
        Public NotOverridable Overrides Sub Load(ByVal stream As Stream)
            Dim tempPath As String = Path.GetTempFileName()
            Using fs As FileStream = File.OpenWrite(tempPath)
                Const COPY_BUFFER_SIZE As Integer = 1024
                Dim buffer As Byte() = New Byte(COPY_BUFFER_SIZE - 1) {}
                Dim read As Integer
                Do While (read = stream.Read(buffer, 0, buffer.Length)) <> 0
                    fs.Write(buffer, 0, read)
                Loop
            End Using
            Load(New FileInfo(tempPath))
        End Sub

        Protected Shared Function MakeTemporaryCopy(ByVal f As FileInfo) As FileInfo
            Dim tempPath As String = CreateTempPath(Path.GetExtension(f.Name))


            Using toFile As FileStream = File.OpenWrite(tempPath)
                Using fromFile As FileStream = New FileStream(f.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite Or FileShare.Delete)
                    Dim buffer As Byte() = New Byte(4095) {}
                    Dim read As Integer
                    Do While (read = CInt(fromFile.Read(buffer, 0, buffer.Length))) > 0
                        toFile.Write(buffer, 0, read)
                    Loop
                End Using
            End Using
            Return New FileInfo(tempPath)
        End Function
    End Class
End Namespace
